package com.xbank.sink.payment.controller;

import cn.hutool.json.JSONObject;
import com.bizmda.bizsip.common.BizException;
import com.bizmda.bizsip.common.BizMessage;
import com.bizmda.bizsip.common.BizUtils;
import com.bizmda.bizsip.converter.Converter;
import com.bizmda.bizsip.sink.connector.Connector;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 史正烨
 */
@Slf4j
@RestController
public class Sink1Controller {
    /* Sink.process()原有方式
    @Autowired
    private Sink sink;
    */
    private Converter converter = Converter.getSinkConverter("payment1-sink");
    private Connector connector = Connector.getSinkConnector("payment1-sink");

    public Sink1Controller() throws BizException {
    }

    /* Sink.process()原有方式
    @PostConstruct
    public void init() {
        try {
            this.sink.init("payment1-sink");
        } catch (BizException e) {
            log.error("Sink1Controller初始化失败！",e);
        }
    }
     */

    @PostMapping(value = "/sink1", consumes = "application/json", produces = "application/json")
    public BizMessage<JSONObject> doService(@RequestBody BizMessage<JSONObject> inMessage, HttpServletResponse response) {
        try {
            byte[] inData = this.converter.pack(inMessage.getData());
            log.debug("打包后消息:\n{}", BizUtils.buildHexLog(inData));
            byte[] outData = this.connector.process(inData);
            log.debug("connector返回消息:\n{}", BizUtils.buildHexLog(outData));
            JSONObject jsonObject = this.converter.unpack(outData);
            log.debug("解包后消息:\n{}", BizUtils.buildJsonLog(jsonObject));
/* Sink.process()原有方式
            jsonObject = this.sink.process(inMessage.getData());
 */
            return BizMessage.buildSuccessMessage(inMessage,jsonObject);
        } catch (BizException e) {
            log.debug("服务端适配器执行出错：{},{}",e.getCode(),e.getMessage());
            return BizMessage.buildFailMessage(inMessage,e);
        }
    }
}